import threading
# 两个线程对一个i，同时进行操作很可能引起混乱
# 加一个锁使得只能存在一个线程操作i
lock = threading.Lock()
i = 0


def sum1():
    global i
    # 上锁
    # if lock.acquire():
    # 简写
    with lock:
        for x in range(100000):
            i += x
            i -= x
    # # 解锁
    # lock.release()
    print('sum1', i)


def sum2():
    global i
    # 上锁
    # if lock.acquire():
    # 简写
    with lock:
        for x in range(100000):
            i += x
            i -= x
    # # 解锁
    # lock.release()
    print('sum2', i)


thr1 = threading.Thread(target=sum1)
thr2 = threading.Thread(target=sum2)
thr1.start()
thr2.start()
thr1.join()
thr2.join()
print(i)
